<?php
namespace app\api\controller;
use Overtrue\EasySms\EasySms;
use think\Db;
class Index extends Api{
        
    /**
     * 获取启动页信息
     * @return type 获取开始页信息
     */
    public function getStartPage(){
        //'DATE_FORMAT(show_time, "%Y-%m-%d %H:%i:%S")
        $host= $this->request->domain();
        $res=Db::name('start_page s')->where(['s.id'=>1])
               ->join('xy_picture p','p.id = s.pic')
               ->field('concat("'.$host.'",p.url) as path,s.show_time,s.name,s.url')
               ->find();
        return $this->result= msback(200,'请求成功',$res);
    }
    /**
     * 获取广告图
     */
    public function getAd(){
        $data= $this->askData;
        $host= $this->request->domain();
        if(!$this->val('getAd')){
            return  $this->result= msback(150,'参数错误','');
        }
        $res= Db::name('ad_place p')
                ->join('xy_ad a','a.place_id = p.id','right')
                ->join('xy_picture i','i.id = a.cover_id','left')
                ->where(['p.name'=>$data['ad_key'],'a.status'=>1,'p.status'=>1])
                ->field('a.url,concat("'.$host.'",i.url) as path,a.title,p.name,a.content,p.show_type')
                ->select();
        return $this->result= $res?msback(200,'请求成功',$res): msback(100,'无数据');
    }
   /**
    * 获取分类信息 
    */
    public function getCateList(){
        $data= $this->askData;
        $where['c.is_delete']=0;
        if(empty($data['is_all'])){
            $where['c.id']=['>',5];
        }
        $host= $this->request->domain();
        $res= Db::name('category c')
                ->join('xy_picture p','p.id = c.icon','left')
                ->where($where)
                ->field('c.id as cat_id,c.key,c.name,c.sort,concat("'.$host.'",p.url) as iconUrl')
                ->order('sort')->select();
        return $this->result= msback(200, '请求成功',$res);
    }
   /**
    * 获取页面信息
    */
    public function getPage(){
        if(!$this->val('getPage')){
            return $this->result= msback(150,'参数错误','');
        }        
        $res= Db::name('page')->where(['key'=> $this->askData['page_key']])
               ->field(' FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time,title,content')
               ->find();
        return $this->result=$res?msback(200,'请求成功',$res):msback(130,'数据不存在','');
    }
    /**
     * 获取公告信息
     */
    public function getNotice(){
        if(!$this->val('getNotice')){
            return $this->result= msback(150,'参数错误','');
        }       
        $res= Db::name('notice')
                ->field('FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time,title,url')
                ->order('create_time desc')
                ->limit($this->askData['offset'].','.$this->askData['per_page'])
                ->select();
        return $this->result=$res?msback(200,'请求成功',$res):msback(130,'数据不存在','');
    }
    /**
     * 获取验证码
     */
    public function getPhoneCode(){
        $data= $this->askData;
        if(!$this->val('getPhoneCode')){
            return $this->result= msback(150,'参数错误','');
        }
        if(!preg_match('/^1[0-9]{10}/',$data['phone'])){
            return $this->result= msback(151,'参数不合规','');
        }
        $identify_code= rand(100000,999999);
        $res= \app\api\model\Api::sendSms($data['phone'], $identify_code);
        if(!$res){
            return $this->result= msback(110,'系统异常，验证码发送失败','');
        }
        if(Db::name('identify_code')->where(['phone'=>$data['phone']])->value('id')){
            $update=[
                'code'=>$identify_code,
                'sure_time'=> time()+600,
                'create_time'=>time(),                
            ];
            $res= Db::name('identify_code')->where(['phone'=>$data['phone']])->update($update);
        }else{
            $insert=[
                'phone'=>$data['phone'],
                'code'=>$identify_code,
                'sure_time'=> time()+600,
                'create_time'=>time(),
            ];
            $res=Db::name('identify_code')->insert($insert);
        }       
        return $this->result=$res?msback(200,'发送成功',['over_time'=>'600']): msback(100,'参数错误，发送失败');
    }
    /**
     * 验证用户登录
     */
    public function checkUser(){
        $data= $this->askData;
        if(!$this->val('checkUser')){
            return $this->result= msback(150,'参数错误','');
        }  
        if(!empty($data['identify_code'])){
            $res=\app\api\model\Api::checkCode($data['username'],$data['identify_code']);
            if(!$res){
                return $this->result=msback(100,'验证码错误','');
            }
            $is_ext= Db::name('user')->where(['username'=>$data['username']])->value('token');
            if($is_ext){
                \app\api\model\Api::updateUserLogin($is_ext);
                return $this->result= msback(200,'登录成功',['token'=>$is_ext,'login_type'=>'login']);
            }else{
                $salt=rand(100000,999999).'xiaoyu';
                $insertData=[
                    'username'=>$data['username'],
                    'password'=> md5($data['identify_code'].$salt),
                    'nickname'=>'游客'. rand(10000,99999),
                    'score'=>0,
                    'salt'=>$salt,
                    'login'=>1,        
                    'token'=> md5($data['username']),
                    'create_time'=> time(),
                    'update_time'=> time(),
                    'reg_time'=>time(),
                ];
                $res= Db::name('user')->insert($insertData);
                return $this->result=$res?msback(200,'注册成功',['token'=>$insertData['token'],'login_type'=>'regist']):msback(100,'注册失败请重试',''); 
            }
        }
        if(!empty($data['password'])){
            $code= Db::name('user')->where(['username'=>$data['username']])->field('password,token,salt')->find();
            if($code['password']== md5($data['password'].$code['salt'])){
                \app\api\model\Api::updateUserLogin($code['token']);
                return $this->result= msback(200,'登录成功',['token'=>$code['token'],'login_type'=>'login']);
            }else{
                 return $this->result=msback(100,'密码错误','');
            }
        }
        return  $this->result= msback(150,'参数错误','');
        
    }
    /**
     * 用户注册密码注册
     */
    public function registPwd(){
        $data= $this->askData;
        if(!$this->val('registPwd')){
            return $this->result= msback(150,'参数错误','');
        }
        $res1= Db::name('user')->where(['username'=>$data['username']])->value('id');
        if($res1){
            return $this->result= msback(151,'该用户已注册请直接登录','');
        }        
        $salt=rand(100000,999999).'xiaoyu';
        $insertData=[
            'username'=>$data['username'],
            'password'=> md5($data['password'].$salt),
            'nickname'=>'游客'. rand(10000000,99999999),
            'score'=>0,
            'salt'=>$salt,
            'login'=>1,        
            'token'=> md5($data['username']),
            'create_time'=> time(),
            'update_time'=> time(),
            'reg_time'=>time(),
        ];
        $res= Db::name('user')->insert($insertData);
        return $this->result=$res?msback(200,'注册成功',['token'=>$insertData['token']]):msback(100,'注册失败请重试','');       
    }
    /**
     * web端注册接口
     */
    public function webRegist(){
        $data= $this->askData;
        if(!$this->val('webRegist')){
            return $this->result= msback(150,'参数错误','');
        }  
        $res1= Db::name('user')->where(['username'=>$data['username']])->value('id');
        if($res1){
            return $this->result= msback(151,'该用户已注册请直接登录','');
        }
        $res2=\app\api\model\Api::checkCode($data['username'],$data['identify_code']);
        if(!$res2){
            return $this->result=msback(100,'验证码错误','');
        }
        if($data['password']!==$data['repassword']){
            return $this->result= msback(151,'两次输入密码不相同','');
        }        
        $salt=rand(100000,999999).'xiaoyu';
        $insertData=[
            'username'=>$data['username'],
            'password'=> md5($data['password'].$salt),
            'nickname'=>'游客'. rand(10000000,99999999),
            'score'=>0,
            'salt'=>$salt,
            'login'=>1,        
            'token'=> md5($data['username']),
            'create_time'=> time(),
            'update_time'=> time(),
            'reg_time'=>time(),
        ];
        $res= Db::name('user')->insert($insertData);
        return $this->result=$res?msback(200,'注册成功',['token'=>$insertData['token']]):msback(100,'注册失败请重试','');            
    }
    /**
     * 设置密码
     */
    public function setPassword(){
        $data= $this->askData;
        if(!$this->val('setPassword')){
            return $this->result= msback(150,'参数错误','');
        }
        if($data['password']!==$data['repassword']){
            return $this->result= msback(151,'两次输入密码不相同','');
        }
        $salt=rand(100000,999999).'xiaoyu';
        $update=[
            'password'=>md5($data['password'].$salt),
            'salt'=>$salt,
        ];       
        $res= Db::name('user')->where(['token'=>$data['token']])->update($update);
        return $this->result=$res?msback(200,'更改成功',''):msback(100,'更改失败','');  
    }
   /**
    *  通过验证码注册
    */
    public function registCode(){
        $data= $this->askData;
        if(!$this->val('registCode')){
            return $this->result= msback(150,'参数错误','');
        }     
        $res1= Db::name('user')->where(['username'=>$data['username']])->value('id');
        if($res1){
            return $this->result= msback(151,'该用户已注册请直接登录','');
        }  
        if(!\app\api\model\Api::checkCode($data['username'],$data['code'])){
            return $this->result= msback(152,'验证码错误','');
        }
        $salt=rand(100000,999999).'xiaoyu';
        $insertData=[
            'username'=>$data['username'],
            'password'=> md5($data['code'].$salt),
            'nickname'=>'游客'. rand(10000000,99999999),
            'score'=>0,
            'salt'=>$salt,
            'login'=>1,        
            'token'=> md5($data['username']),
            'create_time'=> time(),
            'update_time'=> time(),
            'reg_time'=>time(),
        ];
        $res= Db::name('user')->insert($insertData);
        return $this->result=$res?msback(200,'注册成功',['token'=>$insertData['token']]):msback(100,'注册失败请重试','');            
    }
    /**
     * 找回密码
     */
    public function backPassword(){
        $data= $this->askData;
        if(!$this->val('backPassword')){
            return $this->result= msback(150,'参数错误','');
        }         
        $res1= Db::name('user')->where(['username'=>$data['username']])->value('id');
        if(!$res1){
            return $this->result= msback(151,'该用户不存在','');
        } 
        if(!\app\api\model\Api::checkCode($data['username'],$data['code'])){
            return $this->result= msback(152,'验证码错误','');
        }   
        $salt=rand(100000,999999).'xiaoyu';
        $update=[
            'password'=>md5($data['newpassword'].$salt),
            'salt'=>$salt,
        ];
        $res= Db::name('user')->where(['username'=>$data['username']])->update($update);
        return $this->result=$res?msback(200,'更改成功',''):msback(100,'更改失败','');  
    }
    /**
     * 添加修正接口
     */
    public function otherOauthLogin(){
        $data= $this->askData;
        if(!empty($data['qq_code'])){
            $where['qq_code'] = $data['qq_code']; 
            $type='qq';
        } 
        if(!empty($data['wx_code'])){
            $where['wx_code'] = $data['wx_code']; 
            $type='wx';
        } 
        if(!empty($data['wb_code'])){
            $where['wb_code'] = $data['wb_code']; 
            $type='wb';
        } 
        if(empty($where)){
            return $this->result= msback(150,'参数错误','');
        }
        $token= Db::name('user')->where($where)->value('token');
        if($token){
            return $this->result= msback(200,'快速登录成功',['token'=>$token,'is_regiset'=> 0 ]);
        }else{
//            if(empty($data['nickname'])||empty($data['headimg'])){
//                return $this->result= msback(150,'参数错误','');
//            }
//            $imginsert=[
//                   'url'=>getLocalPath($data['headimg']),
//                   'path'=>getLocalPath($data['headimg']),
//                   'md5'=>'',
//                   'sha1'=>'',
//                   'status'=>1,
//                   'create_time'=> time()
//            ];
//            $pic_id=Db::name('picture')->insertGetId($imginsert);
//            //注册用户
//            $salt=rand(100000,999999).'xiaoyu';
//            $token=md5($type.current($where));
//            $insert=[
//                'username'=>$type.'_user_'. rand(10000,99999),
//                'password'=> md5($type.'_user_'. rand(10000,99999).$salt),
//                'nickname'=>$data['nickname'].'_'. rand(100000,999999),
//                'score'=>0,                
//                'salt'=>$salt,
//                'headimg'=>$pic_id,
//                'login'=>1,        
//                'token'=> $token,
//                $type.'_code'=> current($where),
//                'create_time'=> time(),
//                'update_time'=> time(),
//                'reg_time'=> time(),                  
//            ];
//            $is_exit_too= Db::name('user')->where($where)->value('token');
//            if($is_exit_too){
//                $token=$is_exit_too;
//            } else {
//                $res= Db::name('user')->insert($insert);
//            }            
            return $this->result=msback(200,'注册准备',['token'=>'','is_regiset'=> 1]); 
        }
        
    }
    /**
    * 获取分享信息
    */
    public function getUserShareMessage(){
        $data= $this->askData;
        if(!$this->val('getUserShareMessage')){
            return $this->result= msback(150,'参数错误','');
        }     
        $host= $this->request->domain();
        $res= Db::name('article')
                ->where(['id'=>$data['article_id']])
                ->field('content,title,pic_list,id as article_id')
                ->find();
        if(empty($res)){
            return $this->result= msback(151,'非法文章id','');
        }
        if(!empty($res['pic_list'])){
            $res['pic_list']=Db::name('picture')->where("id in (".$res['pic_list'].")")->field("concat('{$host}',url) as url")->select();
        }
        Db::name('article')->where(['id'=>$data['article_id']])->setInc('other_share_num');
        $res['content']= mb_substr(preg_replace('/<.*?>/','',$res['content']),0,30);
        return $this->result= msback(200,'获取成功',$res);        
    }
    //绑定手机号
    public function bindUserPhone(){
        $data= $this->askData;
        if(!$this->val('bindUserPhone')){
            return $this->result= msback(150,'参数错误','');
        }
        $res1=\app\api\model\Api::checkCode($data['username'],$data['code']);
        if(!$res1){
            return $this->result= msback(152,'验证码错误','');
        } 
        $where=[];
        //获取查询条件
        switch ($data['login_type']){
            case 'qq':
                $where['qq_code'] = $data['login_code'];
                $get='qq_code';
                break;
            case 'wx':
                $where['wx_code'] = $data['login_code'];
                $get='wx_code';
                break;
            case 'wb':
                $where['wb_code'] = $data['login_code'];
                $get='wb_code';
                break;
        }
        if(empty($where)){
            return $this->result= msback(153,'请求参数错误','');
        }
        $res3 = Db::name('user')->where(['username' => $data['username']])->value('id');
        if ($res3) {
            $res2 = Db::name('user')->where(['username' => $data['username']])->value($get);
            if (!empty($res2)) {
                return $this->result = msback(153, '此手机已被绑定请更换手机号重试', '');
            }else{
                $res=Db::name('user')
                    ->where(['username'=>$data['username']])
                    ->update($where);
                $token=Db::name('user')->where(['username'=>$data['username']])->value('token');
                return $this->result=$res?msback(200,'绑定成功',['token'=>$token]): msback(100,'操作失败'); 
            }
        }else{
            $salt=rand(100000,999999).'xiaoyu';
            $insertData=[
                'username'=>$data['username'],
                'password'=> md5($data['code'].$salt),
                'nickname'=>'游客'. rand(10000000,99999999),
                'score'=>0,
                'salt'=>$salt,
                'login'=>1,        
                'token'=> md5($data['username']),
                'create_time'=> time(),
                'update_time'=> time(),
                'reg_time'=>time(),
            ];        
            $insertData= array_merge($insertData,$where);
            $res= Db::name('user')->insert($insertData);
            return $this->result=$res?msback(200,'绑定成功',['token'=>$insertData['token']]):msback(100,'注册失败请重试','');  
        }                 
    }
}